package com.demo.webfluxdemo.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.stream.IntStream;

/**
 * @author: lipan
 * @date: 2021/9/21 21:28
 */

@RestController
public class DemoController {



    @RequestMapping("/sync")
    public String  sync(){
        long t1=System.currentTimeMillis();
        String result = getResult();
        System.out.println("同步请求花了:"+(System.currentTimeMillis()-t1)+"ms");
        return result;
    }

    @RequestMapping("/asyncWithMon")
    public Mono<String> asyncWithMon(){

        //相当于消费发布者
        long t1=System.currentTimeMillis();
        Mono<String> result=Mono.fromSupplier(()->getResult());
        System.out.println("异步请求花了:"+(System.currentTimeMillis()-t1)+"ms");
        return  result;
    }


    @RequestMapping(value = "/asyncWithFlux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> asyncWithFlux(){
        Flux<String> flux=Flux.fromStream(IntStream.range(1,5).mapToObj(
               i->{
                   try {
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                  return "flux - - -"+i;
               }
        ));

        return flux;
    }




    /**
     * 模拟耗时操作
     */
    protected String getResult(){

        try {
            Thread.sleep(5000);
            return "success";
        } catch (InterruptedException e) {
            throw  new RuntimeException(e);
        }
    }
}
